package logic

import (
	"context"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/wallet/rpc/walletClient"

	"xialou_platform/services/wallet/api/internal/svc"
	"xialou_platform/services/wallet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WithdrawalListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWithdrawalListLogic(ctx context.Context, svcCtx *svc.ServiceContext) WithdrawalListLogic {
	return WithdrawalListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WithdrawalListLogic) WithdrawalList(req *types.WithdrawalListReq) (resp *respx.PageResp, err error) {
	list, err := l.svcCtx.WalletRpc.WithdrawalList(l.ctx, &walletClient.WithdrawalListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		Status:   req.Status,
		Type:     req.Type,
	})
	if err != nil {
		return nil, err
	}

	res := make([]*types.WithdrawalListResp, 0)
	for _, withdrawal := range list.List {
		var userName string
		var phone string
		switch withdrawal.SourceType {
		case 1:
			agent, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: withdrawal.SourceId})
			if err != nil {
				logx.Errorf("agent(id:%d) not found", withdrawal.SourceId)
				continue
			}
			switch agent.Type {
			case 1:
				userName = agent.RealName
			case 2:
				userName = agent.Company
			}
			phone = agent.Phone
		case 2:
			store, err := l.svcCtx.AgentRpc.StoreById(l.ctx, &agentClient.IdBody{Id: withdrawal.SourceId})
			if err != nil {
				userName = "请联系开发人员"
				phone = "未知"
			} else {
				userName = store.Name
				phone = store.StorePhone
			}
		}

		temp := &types.WithdrawalListResp{
			Id:          respx.IDFrom(withdrawal.Id).ToString(),
			UserName:    userName,
			Type:        withdrawal.SourceType,
			Amount:      withdrawal.Amount,
			Status:      withdrawal.Status,
			Balance:     withdrawal.Balance,
			Phone:       phone,
			CreateTime:  tools.TimeUnixShowLayoutString(withdrawal.CreateTime),
			BankName:    withdrawal.BankName,
			BankNumber:  withdrawal.BankNumber,
			PaymentTime: tools.TimeUnixShowLayoutString(withdrawal.PaymentTime),
			AccountName: withdrawal.AccountName,
			Remark:      withdrawal.Remark,
		}
		res = append(res, temp)
	}
	resp = respx.NewPageResp(req.Page, req.PageSize, list.Total, res)
	return
}
